# -*- coding: utf-8 -*-

"""
DateTime   : 2021/04/11 17:00
Author     : ZhangYafei
Description: 下载高清图片
https://ss.netnr.com/wallpaper
"""
""" 1. 导入所需库 """
import json
import os

import requests
from prettytable import PrettyTable

# 自定义图片文件夹存放路径
images_dir = 'images'
# 若该文件夹不存在，则创建
if not os.path.exists(images_dir):
    os.mkdir(images_dir)

"""" 2. 自定义界面提示信息 """
# 自定义分类ID和分类名称的字典映射关系
image_type_info = {
    0: '最新壁纸', 6: '美女模特', 30: '爱情美图', 9: '风景大片',
    36: '4K专区', 15: '小清新', 26: '动漫卡通', 11: '明星风尚',
    14: '萌宠动物', 5: '游戏壁纸', 12: '汽车天下', 10: '炫酷时尚',
    29: '月历壁纸', 7: '景视剧照', 35: '文字控', 13: '节日美图',
    22: '军事天地', 16: '劲爆体育', 18: 'BABY秀'
}

# 初始化提示信息并打印
# 定义函数
def init_tips_info():
    """" 打印提示信息 """
    table = PrettyTable(['序号1', '壁纸分类1', '序号2', '壁纸分类2'])
    row = []
    for index, key in enumerate(image_type_info, start=1):
        row.extend([key, image_type_info[key]])
        if len(row) == 4:
            table.add_row(row)
            row.clear()
            continue
        if index == len(image_type_info):
            row.extend(['-', '-'])
            table.add_row(row)
    print(table)


# 执行函数
init_tips_info()

""" 3. 获取用户输入 (1)-壁纸分类 (2)-下载数量"""
image_type = input('请选择壁纸分类：>> ')

image_type_desc = None
# 如果输入的图片类型是整数并且是在字典image_type_info中存在，则将image_type_desc赋值为图片类型的描述
#   比如输入的是0, image_type_desc = '最新壁纸'
#       输入的是6，image_type_desc = '美女模特'
# 否则抛出异常,提示用户输入有误
if image_type.isdecimal() and int(image_type) in image_type_info:
    image_type_desc = image_type_info[int(image_type)]
else:
    raise Exception('您输入的类别有误')

count = input('请输入下载数量 >> ')
# 如果输入的下载数量不是10进制整数类型字符串，则抛出异常,提示用户输入有误
if not count.isdecimal():
    raise Exception('您输入的数量必须是整数')

# 若 images/壁纸分类文件夹不存在 则创建
if not os.path.exists(f'{images_dir}/{image_type_desc}'):
    os.mkdir(f'{images_dir}/{image_type_desc}')

"""" 4. 发送请求 """

# 请求头 从浏览器复制
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.75'}

# 请求url
url = 'https://bird.ioliu.cn/v2'

# 构造请求体或参数（get请求可以直接加在url后面 url?k1=v1&k2=v2...）
if image_type == 0:
    params = {
        'url': f'http://wallpaper.apc.360.cn/index.php?c=WallPaper&start=1&count={count}&from=360chrome&a=getAppsByOrder&order=create_time'}
else:
    params = {
        'url': f'http://wallpaper.apc.360.cn/index.php?c=WallPaper&start=1&count={count}&from=360chrome&a=getAppsByCategory&cid={int(image_type)}'}

# 发送请求 用response接收响应信息
response = requests.get(url=url, headers=headers, params=params)

""" 5. 解析数据 """
# 将json字符串转为字典格式  response.text为json(像字典格式的字符串)
result = json.loads(response.text)
"""
result = {
    consume: "10",
    data: [
        {id: "2008041", class_id: "12", resolution: "1920x1080", url_mobile: "",…}
        {id: "2008033", class_id: "15", resolution: "1920x1080", url_mobile: "",…}
        {id: "2008032", class_id: "9", resolution: "1920x1080", url_mobile: "",…}
        {id: "2007786", class_id: "26", resolution: "1920x1200", url_mobile: "",…}
        {id: "2007276", class_id: "9", resolution: "1920x1080", url_mobile: "",…}
        {id: "2007035", class_id: "9", resolution: "2560x1440", url_mobile: "",…}
        {id: "2007033", class_id: "15", resolution: "1920x1080", url_mobile: "",…}
        {id: "2007028", class_id: "36", resolution: "3840x2160", url_mobile: "",…}
        {id: "2007013", class_id: "9", resolution: "1920x1080", url_mobile: "",…}
        {id: "2007011", class_id: "26", resolution: "1920x1080", url_mobile: "",…}
        {id: "2005698", class_id: "14", resolution: "1920x1080", url_mobile: "",…}
        {id: "2005696", class_id: "9", resolution: "1920x1080", url_mobile: "",…}
        ],
    errmsg: "正常",
    errno: "0",
    total: "180",
}
"""
""" 6. 提取数据 """
# 提取字典数据中我们需要的信息 并根据实际需求做数据预处理操作
# 将文件路径和图片地址存储到集合images_list中 images_list为集合套元组，每个元组中包含文件路径和图片地址两个元素
images_list = set()
for image in result['data']:
    """
    image = {
        ...
        class_id: "12"
        create_time: "2020-03-20 14:51:13"
        download_times: "0"
        id: "2008041"
        img_1024_768: "http://browser9.qhimg.com/bdm/1024_768_85/t01753453b660de14e9.jpg"
        img_1280_800: "http://browser9.qhimg.com/bdm/1280_800_85/t01753453b660de14e9.jpg"
        img_1280_1024: "http://browser9.qhimg.com/bdm/1280_1024_85/t01753453b660de14e9.jpg"
        img_1366_768: "http://browser9.qhimg.com/bdm/1366_768_85/t01753453b660de14e9.jpg"
        img_1440_900: "http://browser9.qhimg.com/bdm/1440_900_85/t01753453b660de14e9.jpg"
        img_1600_900: "http://browser9.qhimg.com/bdm/1600_900_85/t01753453b660de14e9.jpg"
        rdata: []
        resolution: "1920x1080"
        tag: "_全部_ _category__  _category_汽车天下_"
        tempdata: ""
        update_time: "2020-03-23 19:31:02"
        url: "http://browser9.qhimg.com/bdr/__85/t01753453b660de14e9.jpg"
        url_mid: "http://browser9.qhimg.com/bdr/__85/t01753453b660de14e9.jpg"
        url_mobile: ""
        url_thumb: "http://browser9.qhimg.com/bdr/__85/t01753453b660de14e9.jpg"
        ...
    }
    """
    filename = image['tag'].replace('_category_', '').replace('_全部_ ', '').strip('_ ').replace(' ', '')
    filename = f'{images_dir}/{image_type_desc}/{filename}_{image["id"]}.jpg'
    images_list.add((filename, image['url']))

"""" 7. 保存数据 """
# 将图片（二进制）数据保存到文件中
for filename, url in images_list:
    response = requests.get(url)

    with open(filename, mode='wb') as f:
        f.write(response.content)

    print(f'{filename} 下载成功！')
